﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace mAdcOW.SharePoint.ChartPicker
{
    [ToolboxItem(false)]
    public class ExcelViewer : WebPart
    {
        [Personalizable(PersonalizationScope.Shared)]
        public string ExcelUrl { get; set; }

        [Personalizable(PersonalizationScope.Shared)]
        public string SelectedChart { get; set; }

        [Personalizable(PersonalizationScope.Shared)]
        [DefaultValue(0)]
        public int ImageHeight { get; set; }

        [Personalizable(PersonalizationScope.Shared)]
        [DefaultValue(0)]
        public int ImageWidth { get; set; }

        [DefaultValue(true)]
        public bool IncludeJquery { get; set; }

        protected override void CreateChildControls()
        {
            if(string.IsNullOrWhiteSpace(ExcelUrl) || string.IsNullOrWhiteSpace(SelectedChart))
            {
                var instructionsLabel = new Label();
                instructionsLabel.Text = "Edit this webpart to select a spreadsheet and chart";
                Controls.Add(instructionsLabel);
            }
            else
            {
                var img = new Image { ImageUrl = GetUri() };
                Controls.Add(img);                
            }            
       }

        public override EditorPartCollection CreateEditorParts()
        {
            var editorPart = new ExcelPickerEditorPart();

            // The ID of the Editor part should be unique. So prefix it with the ID of the Web Part.
            editorPart.ID = ID + "_ExcelConfigurationEditorPart";

            // Create a collection of Editor Parts and add them to the Editor Part collection.
            var editors = new List<EditorPart> {editorPart};
            return new EditorPartCollection(editors);
        }

        private string GetUri()
        {
            var uri = new Uri(SPContext.Current.Site.Url);

            string url = string.Format("/_vti_bin/ExcelRest.aspx{0}/Model/Charts(chartsIndex)?$format=image&chartsIndex={1}", ExcelUrl, HttpUtility.UrlEncode(SelectedChart));

            if (ImageHeight != 0) url += "&$height=" + ImageHeight;
            if (ImageWidth != 0) url += "&$width=" + ImageWidth;

            uri = new Uri(uri, url);
            return uri.OriginalString;
        }
    }
}